<?php
namespace app\index\controller;

use think\facade\View;
use app\BaseController;
use think\worker\Server;
use think\facade\Session;
use app\index\model\Memberfriend;
use app\index\model\Member;
use think\facade\Request;

class Index extends BaseController{
    public function index(){
        // 检查是否登录
        if (!Session::has("user_id")) {
            redirect(url("index/Login/index"))->send();
        }
        $user_id = Session::get("user_id");
        $this->uid = $user_id;
        trace("index");
        $memberInfo = Member::find($user_id);

        // 获取好友列表
        $friend_rt = Memberfriend::getMembers($user_id)->toArray();
        $friend = explode(",",$friend_rt['user_friend']);

        // 获取好友列表信息
        $friendInfo_rt = Member::getMemberInfo([["id","in",$friend]])->toArray();
        foreach ($friendInfo_rt as $key => $value) {
            $friendInfo[$value['id']] = $value;
        }
        
        // 渲染到页面
        View::assign([
            'friendInfo' => $friendInfo,
            'memberInfo' => $memberInfo,
            'uid'        => $user_id
        ]);
        return View::fetch();
    }

    public function bind(){
        // 绑定用户和客户端
        $get = Request::get();
        $result["code"] = 200;

        // 检查参数
        if (empty($get['uid']) || empty($get['client_id'])) {
            $result["message"] = "参数错误";
            $result["data"] = [];
            return json($result);
        }

        // 绑定用户session和client_id
        $connectionInfo = [];
        if (Session::has("connectionInfo")) {
            $connectionInfo = Session::get("connectionInfo");
        }
        $connectionInfo[$get["uid"]] = $get["client_id"];
        Session::set("connectionInfo",$connectionInfo);

        $result["code"] = 200;
        $result["message"] = '成功';
        $result["data"] = $connectionInfo;
        return json($result);
    }
}